<!-- 扫雷 -->
<template>
  <el-dialog v-if="props.show" :model-value="props.show" :title="'【MiniGame】' + data.game_name" top="8vh" width="51%"
    @close="onHideDetails" :close-on-press-escape="false" :destroy-on-close="true" :close-on-click-modal="false">
    <div v-loading="indexStore.moduleLoading">
      <div class="dialogMaxHeight padding20" :class="props.isDisableUser ? 'disableUser' : ''">
        <el-form ref="ruleFormRef" :model="data" :inline="true" :rules="rules" :scroll-to-error="true">
          <form-item title="游戏名称" value="game_name">
            <GameHeaderInfo :game_id="props.checkedItem.game_id" />
          </form-item>
          <form-item title="运营商" :pass="true" value="agent_id" v-show="data.agent_id && !indexStore.is_general_agent">
            <el-select v-model="data.agent_id" placeholder="请选择" filterable @change="chooseOperator">
              <el-option v-for="item in indexStore.agentArray" :key="item.value"
                :label="'【' + item.value + '】' + item.label" :value="item.value" />
            </el-select>
          </form-item>
          <form-item title="游戏水位" :pass="true" value="pool" v-show="data.agent_id && !indexStore.is_general_agent">
            <div class="flexWarp">
              <span class="margin5" v-for="(item, index) in data.serverPoolList" :key="index">
                <el-tag type="danger">{{ item.label }}</el-tag>：
                <el-input-number v-model="item.value" :min="-99999999999999999999" :max="99999999999999999999"
                  :precision="0" placeholder="游戏水位" clearable controls-position="right" />
              </span>
            </div>
          </form-item>
          <form-item title="可赢最大额度" :pass="true" value="win_big_num">
            <el-input-number :min="0" :max="99999999999999999999" :precision="4" v-model="data.win_big_num"
              placeholder="请输入可赢最大额度" clearable controls-position="right" />
            <span class="tipsText"> (玩家游戏中可赢取的最大值)</span>
          </form-item>
          <form-item title="最小雷数" :pass="true" value="min_num">
            <el-select v-model="data.min_num" placeholder="请选择" filterable>
              <el-option v-show="item" v-for="item in 20" :label="item" :value="item" />
            </el-select>
            <span class="tipsText">(最小可选雷数)</span>
          </form-item>
          <form-item title="最大雷数" :pass="true" value="max_num">
            <el-select v-model="data.max_num" placeholder="请选择" filterable>
              <el-option v-show="item && item >= data.min_num" v-for="item in 20" :label="item" :value="item" />
            </el-select>
            <span class="tipsText">(最大可选雷数)</span>
          </form-item>
          <form-item title="进入初始雷数" :pass="true" value="begin_num">
            <el-select v-model="data.begin_num" placeholder="请选择" filterable>
              <el-option v-show="item && item >= data.min_num && data.max_num >= item" v-for="item in 20" :label="item"
                :value="item" />
            </el-select>
            <span class="tipsText">(进入游戏后默认选择雷数)</span>
          </form-item>
          <form-item title="利润率" :pass="true" value="deduction_rate">
            <el-select v-model="data.deduction_rate" placeholder="请选择利润率" filterable>
              <el-option v-show="item" v-for="item in 3" :label="item + '%'" :value="item" />
            </el-select>
            <span class="tipsText">(玩家下注流水*利润率的值；建议值为0%至3%，超过3%会出现押1块钱赢了只能拿0.99元的情况)</span>
          </form-item>
          <form-item title="扫雷倍数上限" :pass="true" value="online_odds">
            <el-input-number :min="0" :max="99999999999999999999" :precision="0" v-model="data.online_odds"
              placeholder="请输入扫雷倍数上限" clearable controls-position="right" />
            <span class="tipsText">(玩家游戏中最大可赢得倍数，当赔率超过该倍数后，玩家点击时直接判定暴雷)</span>
          </form-item>
          <form-item title="押注大小" :pass="true" value="bet_range" :subtract="!props.isDisableUser"
            @addItem="addPressure">
            <div class="flex margin5" v-for="(item, index) in data.pressureList" :key="index">
              <el-input-number :min="0" :max="99999999999999999999" :precision="2" class="width150" v-model="item.num"
                placeholder="请输入押注大小" clearable controls-position="right" />
              <div v-show="!props.isDisableUser" class="reduce-btn reduce-btn_new marginL5"
                @click="reducePressure(index)">-</div>
            </div>
            <span class="tipsText">(玩家可选择的押注额度)</span>
          </form-item>
          <form-item title="水位配置" value="a_hundred_pool" :subtract="!props.isDisableUser" @addItem="addPool"
            v-show="!indexStore.is_general_agent">
            <div class="flexWrap margin5" v-for="(item, index) in data.poolList" :key="index">
              区间上端点:
              <el-input-number v-model="item.min" :min="-99999999999999999999" :max="99999999999999999999"
                :precision="4" class="width150 marginR20" placeholder="区间上端点" clearable :controls="false" />
              概率:
              <el-input-number v-model="item.max" :min="0" :max="99999999999999999999" :precision="2" class="width150"
                placeholder="概率" clearable :controls="false" />
              <div v-show="!props.isDisableUser" class="reduce-btn marginL5" @click="reducePool(index)">-</div>
            </div>
          </form-item>
        </el-form>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer" v-show="!props.isDisableUser">
        <el-button type="info" @click="onHideDetails">取 消</el-button>
        <el-button type="primary" @click="gameSet(ruleFormRef)" v-loading="indexStore.moduleLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { BigWan, BigTimeWan } from '@/utils/math'
import type { MinMax } from './gameType'
import { throttle, selectToLabel } from '@/utils/index'
import { getOperatorSweep, editSweep, getPool, editPool } from '@/api/game'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const props = defineProps({
  show: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  isDisableUser: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  checkedItem: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

watch(
  () => [props.checkedItem, props.show],
  async (value) => {
    if (value[0]) {
      Object.assign(data, props.checkedItem)
    }
    if (value[1]) {
      chooseOperator(props.checkedItem.agent_id, props.checkedItem.game_id)
    }
  },
)

const data = reactive({
  id: 0,
  agent_id: 0,
  game_id: 0,
  game_name: '',
  pool: 0,
  operated_id: indexStore.agentArray[0]?.value,
  win_big_num: 0,
  begin_num: 0,
  min_num: 0,
  max_num: 0,
  deduction_rate: 0,
  online_odds: 0,
  mine_num_range: '',
  pressureList: [{ num: 0 }],
  poolList: [] as MinMax[], // 水位配置
  serverPoolList: [] as any[], // 服务器水位配置
})

// 选择运营商
const chooseOperator = async (id: number, game_id: number) => {
  indexStore.setModuleLoading(true)
  let res = await getOperatorSweep({
    agent_id: id, game_id: game_id
  });
  Object.assign(data, res.data)
  if (data.agent_id) {
    data.serverPoolList = []
    let agent = await getPool({ agent_id: props.checkedItem.agent_id, game_id: props.checkedItem.game_id });
    let keyData = Object.keys(agent.data);
    keyData.forEach((key: string) => {
      data.serverPoolList.push({ label: selectToLabel(indexStore.serverNameList, key), value: BigWan(agent.data[key] ? agent.data[key] : 0), server: key })
    })
  }
  nextTick(() => {
    indexStore.setModuleLoading(false)
  })
}

// 设置
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<typeof data>>({
  win_big_num: [{ required: true, message: '请输入可赢最大额度', trigger: 'blur' }],
  begin_num: [{ required: true, message: '请输入进入初始雷数', trigger: 'blur' }],
  min_num: [{ required: true, message: '请输入最小雷数', trigger: 'blur' }],
  max_num: [{ required: true, message: '请输入最大雷数', trigger: 'blur' }],
  deduction_rate: [{ required: true, message: '请输入扫雷扣点率', trigger: 'blur' }],
  online_odds: [{ required: true, message: '请输入扫雷赔率上限', trigger: 'blur' }]
})
const gameSet = throttle(async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (data.begin_num < data.min_num || data.begin_num > data.max_num) {
        ElMessage.warning('初始雷数必须在最小雷数和最大雷数之间')
        return
      }
      data.mine_num_range = data.min_num + ',' + data.max_num + ',' + data.begin_num
      await editSweep(data);
      if (data.agent_id && !indexStore.is_general_agent) {
        // 按服务器修改水位
        let pools = [] as number[], server = [] as any[];
        data.serverPoolList.forEach((item: any) => {
          pools.push(BigTimeWan(item.value))
          server.push(item.server)
        })
        await editPool({
          agent_id: data.agent_id,
          game_id: data.game_id,
          pools: pools.join(','),
          server_ids: server.join(','),
        })
      }
      ElMessage.success('修改成功')
      emit('onHideDetails', true)
    }
  })
}, 5000)

// 新增押注倍数
const addPressure = () => {
  data.pressureList.push({ num: 0 })
}
// 减少押注倍数
const reducePressure = (index: number) => {
  if (!index && data.pressureList.length == 1) {
    return ElMessage.error('最少保留一个压注额度！')
  }
  data.pressureList.splice(index, 1)
}

// 水位配置
const addPool = () => {
  data.poolList.push({ min: 0, max: 1 })
}
const reducePool = (index: number) => {
  data.poolList.splice(index, 1)
}

// 重置
const emit = defineEmits(['onHideDetails'])
const onHideDetails = () => {
  emit('onHideDetails', false)
}
</script>

<style scoped lang="scss">
.reduce-btn_new {
  position: absolute;
  right: 5px;
  bottom: -3px;
}
</style>